package net.imagine.frontend.spring;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import net.imagine.core.ImageProcessResult;
import net.imagine.core.ResultState;
import net.imagine.core.engine.ImageEngine;
import net.imagine.frontend.ProcedureCaller;
import net.imagine.provider.skyline.LocalImageResizeTask;
import net.imagine.provider.skyline.MultipartImageResizeTask;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class ImageUploadController {
	private static final Log logger = LogFactory.getLog(ImageUploadController.class);
	@Autowired
	private ImageEngine imageEngine;
	private  @Value("${imagine.localStorePath}") String localStorePath;
	private  @Value("${imagine.baseSize1},${imagine.baseSize2}") int[] baseSizes;
	@Autowired(required=false)
	private ProcedureCaller procedureCaller;
	private static final String FILE_PATH_SESSION_KEY = "filepaths";

	public void setBaseSizes(int[] baseSizes) {
		this.baseSizes = baseSizes;
	}

	@RequestMapping(value = "singleupload", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> uploadSingleImage(@RequestParam("file") MultipartFile file,@RequestParam("albumid") Long albumId, HttpSession session) {
		if (file == null) {
			logger.debug("上传图片为空");
			return toJsonMap(false, "", "上传图片失败!", null);
		}
		logger.debug("相册Id:"+albumId);
		MultipartImageResizeTask task = new MultipartImageResizeTask(file, baseSizes, null, false);
		ImageProcessResult result = imageEngine.processSingleImage(localStorePath, task);
		procedureCaller.callProcedure(result);
		if (result.getResultState() == ResultState.SUCCESS) {
			return toJsonMap(true, "", "", null);
		} else {
			return toJsonMap(false, result.getResultState().toString(), "上传图片失败!", null);
		}
	}

	@RequestMapping(value = "batchupload", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> uploadBatchImage(MultipartHttpServletRequest request, HttpSession session) {
		List<MultipartFile> files = request.getFiles("files");
		List<MultipartImageResizeTask> tasks = new ArrayList<MultipartImageResizeTask>();
		for (MultipartFile file : files) {
			if(!file.isEmpty()) {
				tasks.add(new MultipartImageResizeTask(file, baseSizes, null, false));
			}
		}
		if (tasks.size() <= 0) {
			logger.debug("上传图片为空");
			return toJsonMap(false, "", "上传图片失败!", null);
		}
		List<ImageProcessResult> results = imageEngine.processImage(localStorePath, tasks);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", results);
		return toJsonMap(true, "", "", resultMap);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "uploadnotresize", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> uploadWithoutResize(@RequestParam("file") MultipartFile file, @RequestParam("albumid") String albumid, HttpSession session) {
		if (file == null) {
			logger.debug("上传图片为空");
			return toJsonMap(false, "", "上传图片失败!", null);
		}
		List<String> paths = (List<String>) session.getAttribute(FILE_PATH_SESSION_KEY);
		if (paths == null || paths.isEmpty()) {
			paths = new ArrayList<String>();
		}
		String uuid = UUID.randomUUID().toString().toUpperCase();
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		String path = FilenameUtils.concat(localStorePath, uuid + "." + ext);
		File localFile = new File(path);
		try {
			IOUtils.copy(file.getInputStream(), FileUtils.openOutputStream(localFile));
			paths.add(path);
			return toJsonMap(true, "", "", null);
		} catch (Exception e) {
			logger.warn("存放文件到本地失败！", e);
			return toJsonMap(false, "", "上传图片失败!", null);
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "resize", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> uploadBatchResize(HttpSession session) {
		List<String> paths = (List<String>) session.getAttribute(FILE_PATH_SESSION_KEY);
		List<LocalImageResizeTask> tasks = new ArrayList<LocalImageResizeTask>();
		for (String path : paths) {
			tasks.add(new LocalImageResizeTask(path, baseSizes));
		}
		List<ImageProcessResult> results = imageEngine.processImage(localStorePath, tasks);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", results);
		session.removeAttribute(FILE_PATH_SESSION_KEY);
		return toJsonMap(true, "", "", resultMap);
	}

	private Map<String, Object> toJsonMap(boolean isSuccess, String errorCode, String errorMsg,
			Map<String, Object> srcMsg) {
		if (srcMsg == null) {
			srcMsg = new HashMap<String, Object>();
		}
		srcMsg.put("errflag", isSuccess);
		srcMsg.put("errcode", errorCode);
		srcMsg.put("errmsg", errorMsg);
		return srcMsg;
	}

}
